/**
 * Created by houjianhui on 2017/7/19.
 */
'use strict';
wmsCtrl.controller('asnCtrl', ['$scope', 'dropDownService', 'inStorageBillService', function (scope, dropDownService, inStorageBillService) {   //asn 管理 ctrl

    //更多条件默认值
    scope.moreText = scope.constant.moreText.spread;
    //更多条件
    scope.moreClick = function () {
        scope.otherForm = !scope.otherForm;
        if (scope.otherForm) {
            scope.moreText = scope.constant.moreText.packUp;
        } else {
            scope.moreText = scope.constant.moreText.spread;
        }
    }

    //导入弹框
    scope.importData = function () {
        scope.Tools.dialog({
            controller: 'asnCtrl.dialog',
            template: 'templates/inStorageManagement/asnManagement/importData.html',
            closeByDocument: false,
            closeByEscape: false,
            data: {},
            width: 550,
            title: '导入',
            scope: scope
        })
    };

    //验车登记 click
    scope.checkRegClick = function () {

        var indexArr = scope.Tools.getTableSelectItemIndex('.asnTable');  //获取table所选的下标

        var noticeList = scope.Tools.getDataTOIndex(indexArr, scope.noticeList);

        if (noticeList.length > 0) { //选择了数据
            if (noticeList.length > 1) {
                scope.Tools.alert('只能选择一条数据');
                return;
            }

            //判断选择的数据是否正确
            for (var i = 0; i < noticeList.length; i++) {
                if (noticeList[i].inspectStatus != scope.constant.checkCarStatus.noCheck) {
                    scope.Tools.alert('只能选择未验车的数据');
                    return;
                }
            }
        }

        //验车结果下拉值
        var checkResultDropDown = scope.Tools.dropDown.checkCarResultDropDown.concat();
        checkResultDropDown.unshift(scope.constant.defaultDropDownNullData);

        scope.Tools.dialog({
            controller: 'asnCtrl.dialog',
            template: 'templates/inStorageManagement/asnManagement/check-reg.html',
            closeByDocument: false,
            closeByEscape: false,
            data: {
                checkCarResult: checkResultDropDown, //验车结果
                dropDownDefault: { //下拉默认
                    checkCarResult: checkResultDropDown[0]
                },
                checkCar: angular.copy(noticeList[0]),  //验车数据
                vin: noticeList[0] ? noticeList[0].detailList[0].wndVin : null    //vin码
            },
            width: 550,
            title: '验车登记',
            scope: scope
        })
    };

    //打印二维码 click
    scope.printQrClick = function () {
        var indexArr = scope.Tools.getTableSelectItemIndex('.asnTable');  //获取table所选的下标

        var noticeList = scope.Tools.getDataTOIndex(indexArr, scope.noticeList);

        if (noticeList.length === 0) {
            scope.Tools.alert('请选择一条数据');
            return;
        }

        var ids = [];
        for (var i = 0; i < noticeList.length; i++) {
            ids.push(noticeList[i].detailList[0].wndId);
        }

        inStorageBillService.printAsnQrCode(ids)
            .then(function (result) {
                if (result.success) {
                    scope.Tools.dialog({
                        controller: 'asnCtrl.dialog',
                        template: 'templates/inStorageManagement/asnManagement/print-qr-code.html',
                        closeByDocument: false,
                        closeByEscape: false,
                        data: {
                            printList: result.data
                        },
                        width: 550,
                        title: '打印二维码',
                        scope: scope
                    })
                } else {
                    scope.Tools.alert(result.message);
                }
            })
    };

    //打印提车交接单
    scope.printCarMentionedReceiptClick = function () {

        var indexArr = scope.Tools.getTableSelectItemIndex('.asnTable');  //获取table所选的下标

        var noticeList = scope.Tools.getDataTOIndex(indexArr, scope.noticeList);

        scope.Tools.dialog({
            controller: 'asnCtrl.dialog',
            template: 'templates/inStorageManagement/asnManagement/print-car-mentioned-receipt.html',
            closeByDocument: false,
            closeByEscape: false,
            data: {
                noticeList: noticeList
            },
            width: 750,
            title: '打印提车交接单',
            scope: scope
        })
    }

    //初始化对象
    scope.dropDownList = {};    //下拉
    scope.dropDownDefault = {}; //下拉默认值
    //获取货主
    dropDownService.getCustomerInfo()
        .then(function (result) {
            if (result.success) {
                scope.dropDownList.shipper = result.data;
                scope.dropDownList.shipper.unshift(scope.constant.defaultDropDownNullData); //插入空值
                scope.dropDownDefault.shipper = scope.dropDownList.shipper[0];  //设置默认值
            } else {
                scope.Tools.alert(result.message);
            }
        })

    //获取车型
    dropDownService.getVehicleSpec()
        .then(function (result) {
            if (result.success) {
                scope.dropDownList.vehicleSpec = result.data;
                scope.dropDownList.vehicleSpec.unshift(scope.constant.defaultDropDownNullData); //插入空值
                scope.dropDownDefault.vehicleSpec = scope.dropDownList.vehicleSpec[0];  //设置默认值
            } else {
                scope.Tools.alert(result.message);
            }
        })

    //获取车型颜色
    dropDownService.getColorList()
        .then(function (result) {
            if (result.success) {
                scope.dropDownList.carColour = result.data;
                scope.dropDownList.carColour.unshift(''); //插入空值
                scope.dropDownDefault.carColour = scope.dropDownList.carColour[0];  //设置默认值
            } else {
                scope.Tools.alert(result.message);
            }
        })

    /*状态数据*/
    scope.dropDownList = {
        status: scope.Tools.dropDown.checkCarStatusDropDown.concat()    //验车状态
    }
    scope.dropDownList.status.unshift(scope.constant.defaultDropDownNullData);//插入验车状态空数据

    //设置默认值
    scope.dropDownDefault = {
        status: scope.dropDownList.status[0] //状态
    }

    //列表查询接口参数构造
    scope.listParam = function () {

        if (!scope.search) {
            scope.search = {};
        }

        scope.search.pageSize = scope.pageSize;    //设置最大页
        if (!scope.fristSelect) { //不是第一次查询 则设置当前页
            scope.search.pageNo = scope.pageNo;
        } else {  //第一次查询设置为　第一页
            scope.search.pageNo = scope.constant.pageNo;
        }

        if (scope.otherForm) {    //展开了更多
            scope.search.vehicleCode = scope.dropDownDefault.vehicleSpec ? scope.dropDownDefault.vehicleSpec.wndVehicleCode : '';   //车型
            scope.search.customerName = scope.dropDownDefault.shipper ? scope.dropDownDefault.shipper.wnhCustomerName : '';   //货主
            scope.search.colorCode = scope.dropDownDefault.carColour ? scope.dropDownDefault.carColour.wndColorCode : '';  //车型颜色
            scope.search.inspectStatus = scope.dropDownDefault.status.value;    //验车状态
            return scope.search;
        } else {  //没有展开
            return {
                vin: scope.search.vin, //车架号
                pageSize: scope.search.pageSize,   //最大页数
                pageNo: scope.search.pageNo    //当前页
            }
        }
    }

    //列表
    scope.fristSelect = true;   //判断是否是第一次查询
    scope.list = function (params) {
        //设置分页参数
        if (!params) {
            params = {};
        }
        params.pageSize = params.pageSize ? params.pageSize : scope.constant.page.pageSize;
        params.pageNo = params.pageNo ? params.pageNo : scope.constant.page.pageNo;

        inStorageBillService.getAsnList(angular.toJson(params))
            .then(function (result) {
                if (result.success) {
                    scope.noticeList = result.data;
                    if (scope.fristSelect) {
                        scope.Tools.page(document.getElementById('pages'), {
                            pages: result.pageVo.totalPage,
                            curr: result.pageVo.pageNo,
                            count: result.pageVo.totalRecord
                        }, function (obj, first) {
                            scope.fristSelect = first;  //设置状态
                            //初始化多选框
                            scope.Tools.initCheckBox();
                            if (!first) { //判断不是第一次加载
                                var param = scope.listParam();
                                param.pageNo = obj.curr;    //当前页
                                param.pageSize = obj.limit; //最大页
                                scope.pageSize = obj.limit; //设置最大页
                                scope.pageNo = obj.curr; //设置当前页
                                scope.list(param);
                            }
                        })
                    } else {
                        //初始化多选框
                        scope.Tools.initCheckBox();
                    }
                } else {
                    scope.Tools.alert(result.message);
                }
            })

        // inStorageBillService.getAsnList(angular.toJson(params))
        //     .then(function(result){
        //         if(result.success){
        //             scope.asnList = result.data.wmsAsnTempBO;
        //             if(scope.fristSelect){
        //                 scope.Tools.page(document.getElementById('pages'),{
        //                     pages : result.data.wmsAsnTempBOQuery.totalPage,
        //                     curr : result.data.wmsAsnTempBOQuery.pageNo,
        //                     count : result.data.wmsAsnTempBOQuery.totalRecord
        //                 },function(obj, first){
        //                     scope.fristSelect = first;  //设置状态
        //                     //初始化多选框
        //                     scope.Tools.initCheckBox();
        //                     if(!first){ //判断不是第一次加载
        //                         var param = scope.listParam();
        //                         param.pageNo = obj.curr;    //当前页
        //                         param.pageSize = obj.limit; //最大页
        //                         scope.pageSize = obj.limit; //设置最大页
        //                         scope.pageNo = obj.curr; //设置当前页
        //                         scope.list(param);
        //                     }
        //                 })
        //             }else{
        //                 //初始化多选框
        //                 scope.Tools.initCheckBox();
        //             }
        //         }else{
        //             scope.Tools.alert(result.message);
        //         }
        //     })
    }

    //列表
    scope.list();

    //回车按下查询
    scope.searchListKeyDown = function (e) {
        var keycode = window.event ? e.keyCode : e.which;
        if (keycode == 13) {  //回车键
            scope.fristSelect = true;   //设置为第一次查询
            scope.list(scope.listParam());
            e.preventDefault();
        }
    }

    //查询 click
    scope.searchClick = function () {
        scope.fristSelect = true;   //设置为第一次查询
        scope.list(scope.listParam());
    }

    //重置 click
    scope.resetClick = function () {
        scope.search = {};
        scope.dropDownDefault.shipper = scope.dropDownList.shipper[0];  //货主
        scope.dropDownDefault.vehicleSpec = scope.dropDownList.vehicleSpec[0];  //车型
        scope.dropDownDefault.status = scope.dropDownList.status[0];    //状态
        scope.dropDownDefault.carColour = scope.dropDownList.carColour[0];  //颜色
    }

    //刷新 click
    scope.refreshClick = function () {
        scope.searchClick();
    }

    //导入 file change
    scope.fileChange = function (e) {
        scope.setUploaderParam('jminbound/importAsnByExcel', 'file', function (fileItem, response, status, headers) {
            if (status == 200 && response.success) {
                scope.list(scope.listParam());  //刷新列表
                scope.Tools.alert(response.message);
            } else {
                scope.Tools.alert(response.message);
            }
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.close($('div[type=loading]').attr('times'));
            });
        });
        scope.uploadAll();
    }
}])
    .controller('asnCtrl.dialog', ['$scope', 'inStorageBillService', function (scope, inStorageBillService) { // asn controller dialog
        //打印列表
        scope.printListClick = function () {
            if (!scope.Tools.checkPrintInstall()) {   //打印插件检测
                scope.Tools.downLoadPrintPlugIn();    //提示下载打印插件
                return;
            }
            scope.Tools.printHTML($(".dialog-body")[0].outerHTML, 790, 1);
        };

        scope.asnDialogHref = function ($event) {
            $event.stopPropagation();
            inStorageBillService.downloadTemplate().then(function (data) {
                if (data.success) {

                }
            });
        };

        //打印所有的二维码
        scope.printAllQrClick = function () {
            if (!scope.Tools.checkPrintInstall()) {   //打印插件检测
                scope.Tools.downLoadPrintPlugIn();    //提示下载打印插件
                return;
            }

            angular.forEach(scope.ngDialogData.printList, function (v, k) {
                scope.Tools.printQr(v.barcode, v.vin, null, null, 1, scope.constant.userWarehouseType.JM_);
            })
        };

        //验车结果 change
        scope.checkCarChange = function (item) {
            if (item.value == scope.constant.checkCarResult.qualified) {  //合格
                scope.ngDialogData.checkCar.asnCheckDesc = '车辆验证合格';
            } else if (item.value == scope.constant.checkCarResult.unqualified) {  //不合格
                scope.ngDialogData.checkCar.asnCheckDesc = '';
            } else {  //空
                scope.ngDialogData.checkCar.asnCheckDesc = '';
            }
        };

        scope.asnImport = contextPath + 'jminbound/downloadTemplate';

        //导入excel
        scope.stopP = function (e) {
            e.preventDefault();
        };

        scope.fileNameASN = '';
        scope.thatASN = '';
        window.chooseFile = function (that) {
            scope.thatASN = that;
            scope.fileNameASN = that.files[0].name;
            layui.use('layer', function () {
                var layer = layui.layer;
                layer.load();
            });
            angular.element(that).scope().fileChange(that);
        };

        scope.resureUpload = function () {
            window.asd.asdfgg();
        }

        //根据时间查询
        scope.searchByTimeClick = function () {
            inStorageBillService.queryListByTime(scope.printCar)
                .then(function (result) {
                    if (result.success) {
                        scope.ngDialogData.noticeList = result.data;
                    } else {
                        scope.Tools.alert(result.message);
                    }
                })
        }
    }])
    .controller('abnormalManagementCtrl', ['$scope', '$rootScope', '$timeout', 'ngDialog', 'abnormalManagementService', function ($scope, $rootScope, $timeout, ngDialog, abnormalManagementService) {

        layui.use('form', function () {
            var $ = layui.jquery, form = layui.form();

            //全选
            form.on('checkbox(allChoose)', function (data) {
                var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]');
                child.each(function (index, item) {
                    item.checked = data.elem.checked;
                });
                form.render('checkbox');
            });

        });

        //    显示更多条件
        $scope.moreClick = function () {
            $('.otherForm').slideToggle(500);
        };

//    搜索对象
        $scope.search = {
            excpStatus: '',
            excpTypeCode: '',
            excpType: '',
            startGmtCreate: '',
            endGmtCreate: '',
            dealType: '',
            startDealEndTime: '',
            endDealEndTime: '',
            orderNo: '',
            vin: ''
        };
        $scope.resetClick = function () {
            for (var k in $scope.search) {
                $scope.search[k] = '';
            }
        };

//    异常处理
        $scope.dealAbnomal = function () {

            //判断是否有选择
            var orderidArr = [];
            $rootScope.orderidArr = [];
            $rootScope.abm_indexArr = [];
            //获取选中的list列表
            $('.wms_abm_table').find('td i').each(function (i, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    orderidArr.push($(obj).parents('tr').attr('orderid'));
                    $rootScope.abm_indexArr.push($(obj).parents('tr').attr('key'));
                }
            });
            if (orderidArr.length == 0) {
                $scope.Tools.alert('未选择！');
            } else if (orderidArr.length != 1) {
                $scope.Tools.alert('异常处理当前只支持单条操作');
            } else {
                $rootScope.abm_imageList = $scope.tableList;
                ngDialog.open({
                    template: "templates/maintenanceManagement/abnormalManagement/dealAbnormal.html",
                    controller: "dealAbnormalCtrl",
                    title: '异常处理',
                    width: 400,
                    height: 400
                });
            }
        };

        //异常关闭
        $scope.updateToClosed = function () {
            //判断是否有选择
            var orderidArr = [];
            $rootScope.orderidArr = [];
            $rootScope.abm_indexArr = [];
            //获取选中的list列表
            $('.wms_abm_table').find('td i').each(function (i, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    orderidArr.push($(obj).parents('tr').attr('orderid'));
                    $rootScope.abm_indexArr.push($(obj).parents('tr').attr('key'));
                }
            });
            if (orderidArr.length == 0) {
                $scope.Tools.alert('未选择！');
            } else if (orderidArr.length != 1) {
                $scope.Tools.alert('异常关闭只能单选！');
            } else {
                $rootScope.abm_imageList = $scope.tableList;
                ngDialog.open({
                    template: "templates/maintenanceManagement/abnormalManagement/closeAbnormal.html",
                    controller: "closeAbnormalCtrl",
                    title: '异常关闭',
                    width: 380,
                    height: 400
                });
            }
        };

        //查看照片
        $scope.getDetail = function (e) {
            var abmImg = {
                orderId: $(e.target).parents('tr').attr('orderid'),
                excpType: $(e.target).parents('tr').attr('excptype'),
                excpTimestamp: $(e.target).parents('tr').attr('excpTimestamp')
            };
            abnormalManagementService.getImageList(abmImg).then(function (res) {
                if (res.success) {
                    $rootScope.abm_imageList = res.data;
                    ngDialog.open({
                        template: "templates/maintenanceManagement/abnormalManagement/abm_imageList.html",
                        controller: "abm_imageListCtrl",
                        title: '异常图片显示',
                        width: 600
                    });
                    $timeout(function () {
                        $('.ngdialog-content').css('display', 'table')
                    }, 20)
                } else {
                    $scope.Tools.alert(res.message);
                }
            });
        };

        $scope.fristSelect = true;

        //刷新列表
        $scope.refreshClick = function () {
            $scope.getList();
        };

        //    获取列表
        $scope.getList = function () {
            var params = {
                pageNo: $scope.pageNo || 1,
                pageSize: $scope.pageSize || 10,
            };
            params = angular.extend(params, $scope.search);
            var index = layer.load(2);
            abnormalManagementService.queryExcepList(params)
                .then(function (result) {
                    if (result.success) {
                        layer.close(index);
                        $scope.tableList = result.data.dataList;
                        $rootScope.abm_main_tableList = result.data.dataList;
                        if ($scope.fristSelect) {
                            $scope.Tools.page(document.getElementById('pages'), {
                                pages: result.data.page.totalPage,
                                curr: result.data.page.pageNo,
                                count: result.data.page.totalRecord
                            }, function (obj, first) {
                                $scope.fristSelect = first;  //设置状态

                                if (!first) { //判断不是第一次加载
                                    var param = {};
                                    param.pageNo = obj.curr;    //当前页
                                    param.pageSize = obj.limit; //最大页
                                    $scope.pageSize = obj.limit; //设置最大页
                                    $scope.pageNo = obj.curr; //设置当前页
                                    $scope.getList(param);
                                }
                            })
                        }
                    } else {
                        layer.close(index);
                        $scope.Tools.alert(result.message);
                        $scope.tableList = [];
                    }
                })
        };
        $rootScope.abm_getList = $scope.getList;

        $scope.getList();

//    异常描述转义
        $scope.change = function () {

        };
        $scope.formatData = function (obj) {
            var str = '?';
            for (var k in obj) {
                str += '&' + k + '=' + obj[k];
            }
            return str;
        };
        //导出
        $scope.export = function () {
            $scope.excelUrl = contextPath + '/excpManage/importOutExcel' + $scope.formatData(angular.extend({
                whCode: $scope.userInfo.whCode,
                userId: $scope.userInfo.id
            }, $scope.search));
            $timeout(function () {
                document.getElementById('almExport').click();
            }, 20)


        }

//    打印
        $scope.printAbm = function () {
            $rootScope.abm_indexArr_pr = [];
            //获取选中的list列表
            $('.wms_abm_table').find('td i').each(function (i, obj) {
                if ($(obj).parent().hasClass('layui-form-checked')) {
                    $rootScope.abm_indexArr_pr.push($(obj).parents('tr').attr('key'));
                }
            });
            var l = $rootScope.abm_indexArr_pr.length;
            if (l == 0) {
                $scope.Tools.alert('未选择');
            } else if (l > 0) {
                ngDialog.open({
                    template: "templates/maintenanceManagement/abnormalManagement/printAbm.html",
                    controller: "printAbmCtrl",
                    title: '打印',
                    width: 800
                });
            }

        }
    }])
    .controller('abm_imageListCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {

    }])
    .controller('printAbmCtrl', ['$scope', '$rootScope', 'ngDialog', 'Tools', function ($scope, $rootScope, ngDialog, Tools) {
        $scope.abmPrint = function () {
            Tools.printHTML($('.abmPrintMain')[0].outerHTML, 790, 1);
        };
        $scope.close = function () {
            ngDialog.closeAll();
        }
    }])